<template>
  <view class="page">
    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 主要内容 -->
    <view v-else>
      <!-- 订单信息 -->
      <view class="section order-info">
        <view class="section-title">
          <text class="title-icon">📋</text>
          <text class="title-text">订单信息</text>
        </view>
        <view class="order-item">
          <view class="order-header">
            <text class="order-no">订单号：{{ order.orderNo || '加载中...' }}</text>
            <text class="order-amount">¥{{ order.actualAmount || 0 }}</text>
          </view>
          <view class="order-desc">
            <text class="order-type">{{ getOrderTypeText(order.orderType) }}</text>
            <text class="order-status">{{ getStatusText(order.status) }}</text>
          </view>
        </view>
      </view>

    <!-- 退款说明 -->
    <view class="section refund-notice">
      <view class="section-title">
        <text class="title-icon">💡</text>
        <text class="title-text">退款说明</text>
      </view>
      <view class="notice-content">
        <view class="notice-item" v-if="order.orderType === 1">
          <text class="notice-text">• 零食订单配送中申请退款需要商家审核</text>
        </view>
        <view class="notice-item" v-else>
          <text class="notice-text">• 代取订单退款将扣除10%-50%作为接单人补偿</text>
        </view>
        <view class="notice-item">
          <text class="notice-text">• 商家2小时内未处理将自动通过</text>
        </view>
        <view class="notice-item">
          <text class="notice-text">• 退款将原路返回到您的支付账户</text>
        </view>
      </view>
    </view>

    <!-- 退款原因 -->
    <view class="section reason-section">
      <view class="section-title">
        <text class="title-icon">📝</text>
        <text class="title-text">退款原因</text>
      </view>
      <view class="reason-options">
        <view 
          class="reason-item" 
          :class="{ active: selectedReason === reason }"
          v-for="reason in reasonOptions" 
          :key="reason"
          @click="selectReason(reason)"
        >
          <text class="reason-text">{{ reason }}</text>
          <text class="reason-icon" v-if="selectedReason === reason">✓</text>
        </view>
      </view>
      
      <!-- 自定义原因 -->
      <view class="custom-reason" v-if="selectedReason === '其他'">
        <textarea 
          class="reason-input"
          v-model="customReason"
          placeholder="请详细说明退款原因..."
          maxlength="200"
        ></textarea>
        <text class="char-count">{{ customReason.length }}/200</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="btn btn-default" @click="goBack">取消</view>
      <view class="btn btn-primary" @click="submitRefund" :class="{ disabled: !canSubmit }">
        提交申请
      </view>
    </view>
    </view>
  </view>
</template>

<script>
import { applyRefund } from '@/api/refund'
import { getOrderDetail } from '@/api/order'
import { 
  getOrderStatusDisplay,
  getOrderTypeText
} from '@/utils/orderStatus'

export default {
  data() {
    return {
      orderId: null,
      order: {
        orderNo: '',
        actualAmount: 0,
        orderType: 1,
        status: 0,
        deliveryAddress: ''
      },
      selectedReason: '',
      customReason: '',
      reasonOptions: [
        '商品质量问题',
        '配送时间过长',
        '不需要了',
        '地址填错了',
        '重复下单',
        '其他'
      ],
      submitting: false,
      loading: true
    }
  },
  computed: {
    canSubmit() {
      if (!this.selectedReason) return false
      if (this.selectedReason === '其他' && !this.customReason.trim()) return false
      return !this.submitting
    },
    finalReason() {
      return this.selectedReason === '其他' ? this.customReason.trim() : this.selectedReason
    }
  },
  onLoad(options) {
    //console.log('退款申请页面参数:', options)
    if (options.orderId) {
      this.orderId = options.orderId
      // 设置订单类型，用于显示不同的退款说明
      if (options.orderType) {
        this.order.orderType = parseInt(options.orderType)
      }
      this.loadOrderDetail()
    } else {
      uni.showToast({
        title: '订单ID不能为空',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },
  methods: {
    async loadOrderDetail() {
      try {
        this.loading = true
        uni.showLoading({ title: '加载中...' })
        
        //console.log('正在加载订单详情，orderId:', this.orderId)
        const response = await getOrderDetail(this.orderId)
        //console.log('订单详情响应:', response)
        
        // 根据规范，请求拦截器已经返回了data字段的内容
        if (response) {
          this.order = {
            ...this.order,
            ...response
          }
          //console.log('订单数据已更新:', this.order)
        } else {
          throw new Error('订单数据为空')
        }
        
        this.loading = false
        uni.hideLoading()
      } catch (error) {
        console.error('加载订单详情失败:', error)
        this.loading = false
        uni.hideLoading()
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
        
        // 加载失败后返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },

    selectReason(reason) {
      this.selectedReason = reason
      if (reason !== '其他') {
        this.customReason = ''
      }
    },

    async submitRefund() {
      if (!this.canSubmit) return

      try {
        this.submitting = true
        uni.showLoading({ title: '提交中...' })
        
        const response = await applyRefund(this.orderId, this.finalReason)
        
        uni.hideLoading()
        
        //console.log('退款申请响应:', response)
        
        this.submitting = false
        
        uni.showModal({
          title: '申请成功',
          content: response?.message || '退款申请已提交',
          showCancel: false,
          success: () => {
            // 返回订单详情页面
            uni.navigateBack()
          }
        })
        
      } catch (error) {
        console.error('申请退款失败:', error)
        this.submitting = false
        uni.hideLoading()
        
        // 特殊处理订单状态不允许退款的情况
        if (error.message && error.message.includes('不允许退款')) {
          uni.showModal({
            title: '无法申请退款',
            content: error.message,
            showCancel: false,
            success: () => {
              // 返回订单详情页面
              uni.navigateBack()
            }
          })
        } else {
          uni.showToast({
            title: error.message || '申请失败',
            icon: 'none'
          })
        }
      }
    },

    goBack() {
      uni.navigateBack()
    },

    getStatusText(status) {
      const orderType = this.order.orderType || 1
      return getOrderStatusDisplay(orderType, status).text
    },

    getOrderTypeText
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 180rpx;
}

/* 通用样式 */
.section {
  background: #fff;
  margin: 20rpx 32rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.section-title {
  display: flex;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1px solid #f0f0f0;
  
  .title-icon {
    font-size: 32rpx;
    margin-right: 16rpx;
  }
  
  .title-text {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }
}

/* 订单信息 */
.order-info {
  .order-item {
    padding: 32rpx;
  }
  
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
  }
  
  .order-no {
    font-size: 28rpx;
    color: #666;
  }
  
  .order-amount {
    font-size: 32rpx;
    font-weight: 600;
    color: #ff6b35;
  }
  
  .order-desc {
    display: flex;
    gap: 24rpx;
  }
  
  .order-type, .order-status {
    font-size: 24rpx;
    padding: 8rpx 16rpx;
    border-radius: 8rpx;
    background: #f0f0f0;
    color: #666;
  }
}

/* 退款说明 */
.refund-notice {
  .notice-content {
    padding: 32rpx;
  }
  
  .notice-item {
    margin-bottom: 16rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .notice-text {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
  }
}

/* 退款原因 */
.reason-section {
  .reason-options {
    padding: 32rpx;
  }
  
  .reason-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.active {
      .reason-text {
        color: #ff6b35;
      }
      
      .reason-icon {
        color: #ff6b35;
      }
    }
  }
  
  .reason-text {
    font-size: 30rpx;
    color: #333;
  }
  
  .reason-icon {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .custom-reason {
    padding: 0 32rpx 32rpx;
    
    .reason-input {
      width: 100%;
      min-height: 200rpx;
      padding: 24rpx;
      border: 1px solid #e0e0e0;
      border-radius: 12rpx;
      font-size: 28rpx;
      color: #333;
      background: #fafafa;
      box-sizing: border-box;
    }
    
    .char-count {
      display: block;
      text-align: right;
      margin-top: 16rpx;
      font-size: 24rpx;
      color: #999;
    }
  }
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 32rpx;
  background: #fff;
  border-top: 1px solid #e0e0e0;
  gap: 24rpx;
}

.btn {
  flex: 1;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 600;
  
  &.btn-default {
    background: #f0f0f0;
    color: #666;
  }
  
  &.btn-primary {
    background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
    color: #fff;
    
    &.disabled {
      background: #ccc;
      color: #999;
    }
  }
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  
  .loading-text {
    font-size: 28rpx;
    color: #999;
  }
}
</style>
